from QQLoginTool.QQtool import OAuthQQ
from django.shortcuts import render

# Create your views here.
from rest_framework.response import Response
from django.conf import settings
from rest_framework.views import APIView
from rest_framework_jwt.settings import api_settings
from itsdangerous import TimedJSONWebSignatureSerializer as TJS
from oauth.models import OAuthQQUser
from .serializers import OAuthSerializers


class OauthQQloginView(APIView):
    """
        构建qq登录跳转链接
    """

    def get(self, request):
        # 1、获取前端定义好的验证字符串数据
        state = request.query_params.get('next', None)

        # 2、判断前端是否传递验证字符串数据
        if not state:
            state = '/'

        # 3、创建qq对象
        # settings可以获取dev中定义的属性
        qq = OAuthQQ(client_id=settings.QQ_CLIENT_ID, client_secret=settings.QQ_CLIENT_SECRET,
                     redirect_uri=settings.QQ_REDIRECT_URI, state=state)

        # 4、构建跳转连接
        login_url = qq.get_qq_url()

        # 5、返回跳转连接
        return Response({'login_url': login_url})


class OauthView(APIView):

    def get(self,request):

        # 1、获取code值
        code=request.query_params.get('code',None)

        # 2、判断code是否传递过来
        if not code:
            return Response({'errors':'缺少code值'},status=400)

        # 3、通过code值获取access_token值
        state='/'
        # 创建qq对象
        qq = OAuthQQ(client_id=settings.QQ_CLIENT_ID, client_secret=settings.QQ_CLIENT_SECRET,
                     redirect_uri=settings.QQ_REDIRECT_URI, state=state)

        access_token=qq.get_access_token(code)
        # 4、通过access_token值获取opendi值
        openid=qq.get_open_id(access_token)

        # 5. 判断openid是否绑定过美多
        try:
            qq_user = OAuthQQUser.objects.get(openid=openid)
        except:
            # 6. 没绑定过,进入登录页面
            tjs = TJS(settings.SECRET_KEY, 300)
            openid = tjs.dumps({'openid': openid}).decode()


            return Response({'access_token': openid})
        else:
            # 7. 绑定过,登录成功
            user = qq_user.user

            # 生成加密后的token数据
            jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER  # 生成载荷部分
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER  # 生成token

            payload = jwt_payload_handler(user)
            token = jwt_encode_handler(payload)

            return Response({
                'token': token,
                'username': user.username,
                'user_id': user.id,
            })

    def post(self, request):
        # 绑定保存
        data =request.data
        ser = OAuthSerializers(data=data)
        ser.is_valid()
        print(ser.errors)
        ser.save()

        return Response(ser.data)
